package com.own.component.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SynchronizedUtil
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
@Slf4j
public class SynchronizedUtil {

    private static final Map<String, Object> KEY_STRING_MAP = new ConcurrentHashMap<>(8);
    private static final Map<Integer, Object> KEY_INTEGER_MAP = new ConcurrentHashMap<>(8);

    public static void exec(String key, Runnable runnable) {
        synchronized (KEY_STRING_MAP.computeIfAbsent(key, k -> new Object())) {
            try {
                runnable.run();
            } finally {
                KEY_STRING_MAP.remove(key);
            }
        }
    }

    public static void exec(Integer key, Runnable runnable) {
        synchronized (KEY_INTEGER_MAP.computeIfAbsent(key, k -> new Object())) {
            try {
                runnable.run();
            } finally {
                KEY_INTEGER_MAP.remove(key);
            }
        }
    }

}
